package com.jy.servlet;

import com.jy.service.ConsigneeService;
import com.jy.service.impl.ConsigneeSericelmpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class merchant_Add_CommodityImagesSerclet extends HttpServlet {
    private static final Logger log = LoggerFactory.getLogger(merchant_inquire_consigneeServlet.class);
    private ConsigneeService consigneeService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String consignee_name = merchant_Add_MerchandiseServlet.merchant_consignee_name;
        log.debug("consignee_name :",consignee_name);

        consigneeService = new ConsigneeSericelmpl();

        Integer id = consigneeService.selelctconsigneeBymaxid(consignee_name);
        log.debug("进入了getAdd_product_picture");
        String consignee_image = "";
        //判断上传表单是否为multipart/form-data类型
        if(ServletFileUpload.isMultipartContent(request)) {
            try {
                //1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录
                DiskFileItemFactory factory = new DiskFileItemFactory();

                //2. 创建ServletFileUpload对象，并设置上传文件的大小限制。
                ServletFileUpload sfu = new ServletFileUpload(factory);

                sfu.setSizeMax(10 * 1024 * 1024);//以byte为单位    不能超过10M  1024byte = 1kb  1024kb=1M 1024M = 1G
                sfu.setHeaderEncoding("utf-8");

                //3. 调用ServletFileUpload.parseRequest方法解析request对象，得到一个保存了所有上传内容的List对象。
                List<FileItem> fileItemList = sfu.parseRequest(request);
                Iterator<FileItem> fileItems = fileItemList.iterator();

                //4. 遍历list，每迭代一个FileItem对象，调用其isFormField方法判断是否是上传文件
                while (fileItems.hasNext()) {
                    FileItem fileItem = fileItems.next();
                    //普通表单元素
                    if (fileItem.isFormField()) {
                        String name = fileItem.getFieldName();//获取文件名
                        String value = fileItem.getString("utf-8");//设置字符集
                    }
                    //<input type="file">的上传文件的元素
                    else {
                        String fileName = id + ".png";//文件名称
                        System.out.println("原文件名：" + fileName);


                        String realPath = "D:\\wave2003\\Desktop\\homework\\java_Advancedprogramming\\project\\xiaomi_shop_img\\";

                        //5. 调用FileItem的write()方法，写入文件
                        File file = new File(realPath, fileName);
                        System.out.println(file.getAbsolutePath());
                        if (file.exists()){
                            file.delete();
                        }
                        fileItem.write(file);

                        //6. 调用FileItem的delete()方法，删除临时文件
                        fileItem.delete();
                        /*
                         * 存储到数据库时注意
                         *     1.保存源文件名称   Koala.jpg
                         *  2.保存相对路径      image/1478509873038.jpg
                         *
                         */
                        System.out.println(fileName);
                        request.setAttribute("image_name", fileName);
                        request.setAttribute("image_path", fileName);
                        consignee_image = "/xiaomi_shop_img/" + id + ".png";
                        boolean favg = consigneeService.updateconsigneeImg(consignee_name,consignee_image);
                        request.setAttribute("merchantSon_state",favg);
                        request.getRequestDispatcher("/merchantSon.jsp").forward(request,response);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//    public static void main(String[] args) {
//        String consignee_image = "name=37.png, StoreLocation=D:\\tools\tomcat-8.5.56\\temp\\upload_3939d714_fc3a_4218_88f8_d221ffbc2718_00000000.tmp, size=147305 bytes, isFormField=false, FieldName=uploadFile";
//        log.debug(consignee_image.substring(5,consignee_image.indexOf(",")));
//    }
}
